<template>
  <div class="search-list">
    <scroll
    v-if="list.length"
    ref='search_list_scroll'
    :pullup='true'
    :beforeScroll='true'
    @scrollToEnd='getMore'
    @scrollWillStart='blur'
    >
    <ul>
      <!-- 歌曲一定显示，歌手不一定显示 -->
      <li v-for='item in list' class='search-item' v-show='!item.type || showSinger' @click='selectItem(item)'>
        <i class='icon' :class='{"icon-mine": item.type, "icon-music": !item.type}'></i>
        <span class='text' v-if='!item.type'>{{item.name}}-{{item.singer}}</span>
        <span class='text' v-else>{{item.singername}}</span>
      </li>
        <loading text='' v-show="loading"></loading>
    </ul>
  </scroll>
    <div class="no-result-wrapper">
      <noresult title='查询结果为空' v-if='!loading && list.length === 0 '></noresult>
    </div>
</div>
</template>
<script>
  import { mapMutations, mapActions, mapGetters } from 'vuex';
  import Singer from '@/common/js/singer';
  import scroll from '@/base/scroll';
  import { getSearchList } from '@/api/search';
  import { createSong } from '@/common/js/song';
  import loading from '@/base/loading';
  import noresult from '@/base/no-result';
  import { saveSearchItem } from '@/common/js/cache';

  const TYPE_SINGER = 'singer';
  const PER_PAGE = 20;

  export default {
    name: 'search-list',
    props: {
      showSinger: {
        type: Boolean,
        default: true,
      },
      query: {
        type: String,
        default: '',
      },
    },
    computed: {
      ...mapGetters(['searchHistory']),
    },
    data() {
      return {
        page: 1,
        list: [],
        loading: false,
        hasMore: false,
      };
    },
    methods: {
      selectItem(item) {
        if (item.type) {
          // 选中歌手,跳转到对应
          this.$router.push({
            path: `/search/${item.singermid}`,
          });
          const singer = new Singer({ id: item.singermid, name: item.singername });
          // 对应到mapMutations, 这里又用到了Singer构造器
          this.SET_SINGER(singer);
          this.SET_SEARCH_HISTORY(saveSearchItem(singer));
        } else {
          // 在播放list中插入该song
          this.insertSong(item);
          this.SET_SEARCH_HISTORY(saveSearchItem(item));
        }
        // todo 这里派发给父组件处理?
        // const hisList = this.searchHistory.slice(0);
        // hisList.unshift(item);
        // this.SET_SEARCH_HISTORY(saveSearchItem(item));
      },
      refresh() {
        this.$refs.search_list_scroll && this.$refs.search_list_scroll.refresh();
      },
      getMore() {
        if (!this.hasMore) {
          alert('没有更多了...');
          return;
        }
        this.page += 1;
        this._getResult(this.page);
      },
      blur() {
        this.$emit('scrollWillStart');
      },
      _checkMore(arr) {
        this.hasMore = arr.length === PER_PAGE || arr.length === PER_PAGE + 1;
      },
      _normalizeSong(arr) {
        const res = [];
        arr.forEach((item) => {
          res.push(createSong(item));
        });
        return res;
      },
      _getResult(page) {
        this.loading = true;
        const commonParams = {
          w: this.query,
          page,
          zhida: true,
          perpage: PER_PAGE,
        };
        // const params = Object.assign({}, commonParams, {
        //   page,
        // });
        getSearchList(commonParams).then((res) => {
          const songList = this._normalizeSong(res.song.list);
          // 如果可以找到该歌手放在list首位
          if (res.zhida && res.zhida.singerid) {
            songList.unshift({ ...res.zhida, type: TYPE_SINGER });
          }
          this.loading = false;
          this._checkMore(songList);
          this.list = this.list.concat(songList);
          this.refresh();
        });
      },
      ...mapMutations(['SET_SINGER', 'SET_SEARCH_HISTORY']),
      ...mapActions(['insertSong']),
    },
    watch: {
      query(now) {
        // 重置操作
        this.page = 1;
        this.list = [];
        if (now === '') {
          return;
        }
        // 开始搜索列表(第一页)
        this._getResult(this.page);
      },
    },
    components: {
      scroll,
      loading,
      noresult,
    },
  };
</script>
<style lang='stylus' scoped>
@import '~styl/var'
@import '~styl/mixin'
.search-list
  height 100%
  .search-item
    display flex
    padding-bottom 20px
    .icon
      flex-basis 30px
      width 30px
      font-size: 14px
      color: $color-text-d
    .text
      flex 1
      no-wrap()
      overflow: hidden
      font-size: $font-size-medium
      color: $color-text-d
  .no-result-wrapper
    center(absolute)
</style>
